package com.hsd.controller;

import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hsd.pojo.History;
import com.hsd.pojo.Result;
import com.hsd.service.HistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
 * ClassName: HistoryController
 * Package: com.hsd.controller
 * Description:
 * @ Author zyt
 * @ Create 2025/4/10
 * @ Version 1.0
 */
@RestController
@Slf4j
public class HistoryController {
    @Autowired
    private HistoryService historyService;

    /**
     * 获取历史记录
     *
     * @return 历史记录
     */
    @GetMapping("/calculate/history")
    public Result getHistory() {
        try {
            List<History> histories = historyService.list();
            if (CollectionUtils.isEmpty(histories)) {
                return Result.success(Collections.emptyList());
            }

            List<Map<String, String>> result = histories.stream()
                    .map(history -> {
                        Map<String, String> expression = new HashMap<>();
                        expression.put("data", history.getHistory());
                        return expression;
                    })
                    .filter(map -> !map.containsValue(null)) // 过滤空值
                    .collect(Collectors.toList());

            return Result.success(result);
        } catch (ServiceException e) {
            log.error("获取历史记录失败", e);
            return Result.error("系统繁忙，请稍后再试");
        }
    }


    public void saveHistory(String epx) {
        History history = new History();
        history.setHistory(epx);
        historyService.save(history);
    }


}
